﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using SEOBlog.Web.Models.Admin;

namespace SEOBlog.Web.Helpers
{
    public static class TreeViewHelper
    {
        public static string BuildTreeView(IEnumerable<PageTreeViewNode> nodes)
        {
            if(nodes == null)
            {
                throw new ArgumentNullException("nodes");
            }

            var root = nodes.Where(node => string.IsNullOrEmpty(node.ParentId));
            var treeNodes = nodes.Where(node => !string.IsNullOrEmpty(node.ParentId));
            
            var tree = new NaryTree<PageTreeViewNode>(root);
            foreach (var treeViewPageNode in treeNodes)
            {
                tree.Add(treeViewPageNode);
            }

            var result = new StringBuilder();

            tree.TraverseTree(
                x => result.Append(string.Format("<li>{0}<ul>", x.Name)),
                x => result.Append("</ul></li>"),
                x => result.Append(string.Format("<ul> <a href=\"{0}\">{1}</a>)", x.Url, x.Name)),
                x => result.Append("</ul>"),
                x => result.Append(string.Format("<li><a href=\"{0}\">{1}</a><li>", x.Url, x.Name)));

            return result.ToString();
        }
    }
}